﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DAL.Helpers;
using Model.Entities;
using Model.RepositoryInterfaces;
using Model.ViewModels;
using NHibernate;

namespace DAL.Repositories
{
    public class IntervalRepository:IIntervalRepository
    {
        #region Implementation of IIntervalRepository

        public void Create(Interval interval)
        {
            using (var session = NHibernateHelper.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    try
                    {
                        session.Save(interval);
                        transaction.Commit();
                    }
                    catch (ADOException exception)
                    {
                        throw new Exception(exception.Message);
                    }
                }
            }
        }

        public Interval Read(int id)
        {
            using (var session = NHibernateHelper.OpenSession())
            {
                var interval = session.Get<Interval>(id);
                return interval;
            }
        }

        public IList<IntervalVm> ReadAllByCategory(IntervalCategory category)
        {
            using (var session = NHibernateHelper.OpenSession())
            {
                var query = session.CreateQuery("from Interval where Category = :category").SetParameter("category", category);
                var intervalList = query.List<Interval>();

                return intervalList.Select(interval => new IntervalVm()
                {
                    Id = interval.Id, 
                    Name = interval.Name
                }).ToList();
            }
        }

        #endregion
    }
}
